import 'package:flutter/material.dart';
import 'package:flutter_getx_cms/utils/size_extension.dart';
import 'package:get/get.dart';
import 'package:isar/isar.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';

import '../../components/task_card/task_card.dart';
import '../../components/webview_flutter/webview_container.dart';
import '../../res/assets_path.dart';
import '../../utils/locale_controller.dart';
import '../../utils/state_controller.dart';
import 'logic.dart';

class GetHomePage extends StatelessWidget {
  GetHomePage({Key? key}) : super(key: key);

  /// 使用Get.put()实例化你的类，使其对当下的所有子路由可用。
  final logic = Get.put(GetHomeLogic());

  @override
  Widget build(BuildContext context) {
    final themeData = TDTheme.of(context);
    final lc = Get.find<LocaleController>();

    return Scaffold(
      appBar: AppBar(
        title: Text("首页".tr),
        elevation: 0, // 设置为0取消阴影
        backgroundColor: themeData.brandColor6,
        automaticallyImplyLeading: false,
        actions: [
          GestureDetector(
            child: Row(
              children: [
                Obx(() => TDText(
                      lc.language.value.text,
                      style: const TextStyle(color: Colors.white),
                      font: themeData.fontLinkSmall,
                    )),
                const Icon(Icons.keyboard_arrow_down, size: 18),
              ],
            ),
            onTap: () => _showLanguagePicker(lc),
          ),
        ],
      ),
      body: Obx(() => _buildBody(context)),
    );
  }

  void _showLanguagePicker(LocaleController lc) {
    TDPicker.showMultiPicker(
      Get.context!,
      initialIndexes: [lc.language.value.index],
      leftText: '取消'.tr,
      rightText: '确定'.tr,
      onConfirm: (selected) {
        lc.changeLanguage(selected[0]);
        Navigator.of(Get.context!).pop();
      },
      data: [lc.languageTextList],
    );
  }

  _buildBody(BuildContext context) {
    return Column(
      children: [
        _buildMainInfo(Get.context!),
        Expanded(child: _buildTodoList())
      ],
    );
  }

  _buildMainInfo(context) {
    return Container(
      height: 200,
      width: double.infinity,
      color: TDTheme.of(Get.context!).brandColor6,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start, // 左对齐
        children: [_buildUserInfo(context), Spacer(), _buildTopTasks()],
      ),
    );
  }

  _buildUserInfo(context) {
    return Padding(
      padding: const EdgeInsets.all(32),
      child: Row(
        children: [
          TDAvatar(
            avatarSize: 80,
            type: TDAvatarType.normal,
            defaultUrl: R.IMAGES_AVATAR_PNG,
            // avatarUrl: uc.user.value.avatar,
          ),
          24.widthSizedBox,
          Expanded(child: _buildUserDetails(context)),
        ],
      ),
    );
  }

  _buildUserDetails(context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            TDText(
              'owner'.tr,
              style: const TextStyle(
                  color: Colors.white,
                  fontSize: 20,
                  fontWeight: FontWeight.bold),
            ),
          ],
        ),
        4.heightSizedBox,
        _buildDepartmentAndRole(context),
      ],
    );
  }

  _buildDepartmentAndRole(BuildContext context) {
    final themeData = TDTheme.of(context);
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        TDText(
          '${'部门'.tr} :  未设置部门',
          style: const TextStyle(color: Colors.white, height: 2),
          font: themeData.fontLinkSmall,
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
        ),
        TDText(
          '${'角色'.tr} :  进出口部中方经理',
          style: const TextStyle(color: Colors.white, height: 2),
          font: themeData.fontLinkSmall,
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
        ),
      ],
    );
  }

  _buildTopTasks() {
    final themeData = TDTheme.of(Get.context!);
    return Container(
      padding: const EdgeInsets.only(top: 8, left: 16, right: 16, bottom: 10),
      decoration: const BoxDecoration(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(20), // 左上角圆角
          topRight: Radius.circular(20), // 右上角圆角
        ),
        color: Colors.white,
      ),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              TDText(
                "待处理流程",
                font: themeData.fontTitleMedium,
                fontWeight: FontWeight.w600,
              ),
              TDButton(
                text: '更多'.tr,
                size: TDButtonSize.small,
                type: TDButtonType.text,
                textStyle: const TextStyle(fontWeight: FontWeight.w400),
                onTap: () {
                  logic.stateController.eventBus.fire(UserTabbarChangeEvent(1));
                },
              ),
            ],
          )
        ],
      ),
    );
  }

  _buildTodoList() {
    return SmartRefresher(
      controller: logic.refreshController,
      enablePullDown: true,
      enablePullUp: true,
      onRefresh: logic.onRefresh,
      onLoading: logic.onLoadMore,
      header: WaterDropHeader(),
      footer: ClassicFooter(),
      child: ListView.builder(
        itemCount: logic.items.length,
        itemBuilder: (context, index) {
          return ListTile(title: _buildTask(logic.items[index]));
        },
      ),
    );
  }

  // 构建单个任务卡片
  Widget _buildTask(String text) {
    return GestureDetector(
      child: Container(
        margin: const EdgeInsets.symmetric(vertical: 4),
        child: TaskCard(),
      ),
      onTap: () => {
        // 通过 Get.to() 传递参数
        Get.toNamed("/webview", arguments: {'title': 'bing'})
      },
    );
  }
}
